import {
	getStore,
	setStore,
} from '@/common/util';

import {
	getCartItems,
	addCartItem,
	updateCartItem,
	deleteCartItem
} from '@/api/buy/cart'

const cart = {
	state: {
		cartItems: getStore({
		  name: '$sc_cartItems'
		}) ||  []
	},
	mutations: {
		loadCartItem: function(state, data) {
			state.cartItems = data;
			setStore({
			name: '$sc_cartItems',
			content: state.cartItems,
			type: 'session'
			})
		},
		addCart: function(state, data) {
			console.log("xxx" + JSON.stringify(state));
			
			state.cartItems.push(data);
			setStore({
			name: '$sc_cartItems',
			content: state.cartItems,
			type: 'session'
			})
		},
		deleteCart(state, index) {
			state.cartItems.splice(index, 1);
			setStore({
			name: '$sc_cartItems',
			content: state.cartItems,
			type: 'session'
			})
		},
		updateCart(state, data) {
			
			console.log(JSON.stringify(data));
			const {
				index,
				key,
				value
			} = data;
			state.cartItems[index][key] = value;
			setStore({
				name: '$sc_cartItems',
				content: state.cartItems,
				type: 'session'
			})
		}
	},
	actions: {
		loadCartAction: function({
			commit,
			state
		}, userId) {
			return new Promise((resolve, reject) => {
				if(state.cartItems.length <= 0 )
				{
					getCartItems({"partyId": userId, visitedId: ""}).then(res => {
						console.log(JSON.stringify(res))
						if(res.status == 200 ) {
							commit("loadCartItem",res.data)
						} else {
							reject(res.data);
						}
						resolve();
					}).catch(error => {
							reject(error)
						});
				} else {
					resolve();
				}
				
			})
		},
		updateCartAction: function({
			commit,
			state
		}, cmmitItem) {
			return new Promise((resolve, reject) => {
				if(cmmitItem.key != "xmove")
				{
					updateCartItem(cmmitItem.cartItem).then(res => {
						commit("updateCart", {index:cmmitItem.index,
						key:cmmitItem.key,
						value:cmmitItem.value});
						console.log("updateCart resolve......")
						resolve();
					}).catch(error => {
						reject(error)
					}) 
				} else 
				{
					commit("updateCart", commit("updateCart", {index:cmmitItem.index,
						key:cmmitItem.key,
						value:cmmitItem.value}));
						resolve();
				}
				
				
			})
		},
		addCartAction: function({
			cmmit,
			state
		}, cartItem) {
			return new Promise((resolve, reject) => {
				addCartItem(cartItem).then(res => {
					console.log(JSON.stringify(res));
					commit("addCart", cartItem)
					resolve();
				}).catch(error => {
					reject(error)
				}) 
			})
		},
		deleteCartAction: function({
			cmmit,
			state
		}, cartItem) {
			return new Promise((resolve, reject) => {
				deleteCartItem(cartItem.cartItemId).then(res => {
					console.log(JSON.stringify(res));
					commit("deleteCart", cartItem.index)
					resolve();
				}).catch(error => {
					reject(error)
				}) 
			})
		},
	}
}



export default cart
